//
//  ZYQChatMessageViewController.m
//  小庆聊天室
//
//  Created by 张毓庆 on 13-12-11.
//  Copyright (c) 2013年 张毓庆. All rights reserved.
//

#import "ZYQChatMessageViewController.h"
#import <CoreData/CoreData.h>
#import "ZYQAppDelegate.h"
#import "ZYQLoginUser.h"
#import "NSString+Helper.h"
#import "ZYQChatMessageCell.h"


@interface ZYQChatMessageViewController ()<UITextFieldDelegate,NSFetchedResultsControllerDelegate, UITableViewDataSource, UITableViewDelegate>
{
    // 查询结果控制器
    NSFetchedResultsController *_fetchedResultsController;
}
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong , nonatomic) IBOutlet NSLayoutConstraint *baseKeyBoardConstraint;
@property (strong , nonatomic) IBOutlet NSLayoutConstraint *englishKeyBoardConstraint;

@end

@implementation ZYQChatMessageViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    // 1. 利用通知中心监听键盘的变化（打开、关闭、中英文切换）
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    // 2. 初始化查询结果控制器
    [self setupFetchedResultsController];
}
#pragma mark - 初始化查询结果控制器
- (void)setupFetchedResultsController
{
    // 1. 实例化数据存储上下文
    NSManagedObjectContext *context = [[xmppDelegate xmppMessageArchivingCoreDataStorage] mainThreadManagedObjectContext];
    
    // 2. 定义查询请求
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"XMPPMessageArchiving_Message_CoreDataObject"];
    
    // 3. 定义排序
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:YES];
    
    // 4. 定义查询条件(谓词，NSPredicate)
    // 查询来自与hello发给admin的消息
    request.predicate = [NSPredicate predicateWithFormat:@"bareJidStr CONTAINS[cd] %@ AND streamBareJidStr CONTAINS[cd] %@", _bareJidStr,[ZYQLoginUser sharedZYQLoginUser].myJIDName];
    [request setSortDescriptors:@[sort]];
    
    // 5. 实例化查询结果控制器
    _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
    
    // 6. 设置代理
    _fetchedResultsController.delegate = self;
    
    // 7. 执行查询
    NSError *error = nil;
    if (![_fetchedResultsController performFetch:&error]) {
        NSLog(@"查询数据出错 - %@", error.localizedDescription);
    } else {
        [self scrollToTableBottom];
    }
}
#pragma mark - 查询结果控制器代理方法
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    // 刷新表格
    [self.tableView reloadData];
    
    // 滚动到表格末尾
    [self scrollToTableBottom];
}


#pragma mark - 键盘边框大小变化
- (void)keyboardChangeFrame:(NSNotification *)notification
{
//    NSLog(@"%@", notification.userInfo);
    
    // 根据跟踪发现，使用userInfo的UIKeyboardFrameEndUserInfoKey数据可以判断键盘的大小和目标位置
    
    // 1. 获取键盘的目标区域
    NSDictionary *info = notification.userInfo;
    CGRect rect = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat duration = [info[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    
    // 2. 根据rect的orgion.y可以判断键盘是开启还是关闭
    if (rect.origin.y == [UIScreen mainScreen].bounds.size.height)
    {
        NSArray *array = [self.view constraints];
        
        if (![array containsObject:self.englishKeyBoardConstraint])
        {
            [self.view addConstraint:self.englishKeyBoardConstraint];
        }
        
        if (![array containsObject:self.baseKeyBoardConstraint])
        {
            [self.view addConstraint:self.baseKeyBoardConstraint];
        }
        
    }
    else
    {
        // 打开键盘或者中英文切换
        // 根据目标位置的高度判断键盘类型
        if (rect.size.height == 216)
        {
            NSArray *array = [self.view constraints];
            
            if (![array containsObject:self.englishKeyBoardConstraint])
            {
                [self.view addConstraint:self.englishKeyBoardConstraint];
            }
            
            if ([array containsObject:self.baseKeyBoardConstraint])
            {
                [self.view removeConstraint:self.baseKeyBoardConstraint];
            }
            
        }
        else if (rect.size.height == 252)
        {
            NSArray *array = [self.view constraints];
            if ([array containsObject:self.baseKeyBoardConstraint])
            {
                [self.view removeConstraint:self.baseKeyBoardConstraint];
            }
            
            if ([array containsObject:self.englishKeyBoardConstraint])
            {
                [self.view removeConstraint:self.englishKeyBoardConstraint];
            }
        }
    }
    
    // 用自动布局系统实现动画，调整位置
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        [self scrollToTableBottom];
    }];
}

#pragma mark - textfield的代理方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
//    [self.view endEditing:YES];
    
    // 发送消息
    // 1. 取出文本并截断空白字符串
    NSString *str = [textField.text trimString];
    
    // 2. 实例化XMPPMessage，以便发送
    NSString *jidStr = _bareJidStr;
    XMPPMessage *message = [XMPPMessage messageWithType:@"chat" to:[XMPPJID jidWithString:jidStr]];
    
    [message addBody:str];
    
    [[xmppDelegate xmppStream] sendElement:message];
    
    return YES;
}


#pragma mark - 表格操作方法
#pragma mark 滚动到表格的末尾
- (void)scrollToTableBottom
{
    // 要选中滚动到最末一条记录
    // 1. 知道所有的记录行数
    id <NSFetchedResultsSectionInfo> info = _fetchedResultsController.sections[0];
    NSInteger count = [info numberOfObjects];
    
    if (count <= 0) {
        return;
    }
    
    // 2. 根据行数实例化indexPath
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(count - 1) inSection:0];
    // 3. 选中并滚动到末尾
    [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionBottom];
}

#pragma mark - UITableView数据源方法
#pragma mark 表格行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    id <NSFetchedResultsSectionInfo> info = _fetchedResultsController.sections[section];
    
    return [info numberOfObjects];
}

#pragma mark 表格行
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *FromID = @"ChatFromCell";
    static NSString *ToID = @"ChatToCell";
    
    XMPPMessageArchiving_Message_CoreDataObject *message = [_fetchedResultsController objectAtIndexPath:indexPath];
    
    ZYQChatMessageCell *cell = nil;
    
    if (message.isOutgoing) {
        cell = [tableView dequeueReusableCellWithIdentifier:FromID];
    } else {
        cell = [tableView dequeueReusableCellWithIdentifier:ToID];
    }
    
    // 设置单元格
    cell.contentLabel.text = message.body;
    
    if (message.isOutgoing) {
        cell.headImageView.image = self.myImage;
    } else {
        cell.headImageView.image = self.bareImage;
    }

    return cell;
}

#pragma mark - 表格的代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80.0; 
}

@end
